package com.en.effectiveJava.chapter2.cancleReference6;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * 简单的栈实现的例子
 * Create by EN
 * On 4/06/18 12:53 PM
*/
public class Stack {

    //存放元素
    private Object[] elements;

    //栈中当前有效元素的个数
    private int size = 0;

    //默认栈的大小
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    public Stack() {
        elements = new Object[DEFAULT_INITIAL_CAPACITY];
    }

    //存放元素方法
    public void push(Object e) {
        ensureCapacity();
        elements[size++] = e;
    }

    //取出元素方法
    //存在内存泄露，elements[size] 元素的引用对象将会被保持。无意识的对象保持(unintentional object retention)
    public Object popBad() {
        if (size == 0)
            throw new EmptyStackException();
        return elements[--size];
    }

    //只要一个单元被弹出栈，指向它的引用就过期了
    public Object pop() {
        if (size == 0)
            throw new EmptyStackException();
        Object element = elements[--size];
        elements[size] = null;
        return element;
    }

    //判断栈长度是否足够
    private void ensureCapacity() {
        if (size == elements.length)
            elements = Arrays.copyOf(elements, 2 * size + 1);
    }

    public Object[] getElements() {
        return elements;
    }

}
